﻿namespace App_Clinique.ClassLibrary.DbContext
{
    using App_Clinique.ClassLibrary.Entities;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.Entity;
    using System.Data.Entity.ModelConfiguration.Conventions;
    using System.Data.SqlClient;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public class App_cliniqueContext : DbContext
    {
        public DbSet<Actualite> Actualite { get; set; }
        public DbSet<Consultation> Consultation { get; set; }
        public DbSet<Document> Document { get; set; }
        public DbSet<Medicament> Medicament { get; set; }
        public DbSet<OrdonnancesMedicaments> OrdonnancesMedicaments { get; set; }
        public DbSet<Patient> Patient { get; set; }

        public App_cliniqueContext()
            : base("App_cliniqueContext")
        {

        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Actualite>().ToTable("Actualite", "dbo");
            modelBuilder.Entity<Consultation>().ToTable("Consultation", "dbo");
            modelBuilder.Entity<Document>().ToTable("Document", "dbo");
            modelBuilder.Entity<Medicament>().ToTable("Medicament", "dbo");
            modelBuilder.Entity<OrdonnancesMedicaments>().ToTable("OrdonnancesMedicaments", "dbo");
            modelBuilder.Entity<Patient>().ToTable("Patient", "dbo");

            /****************************************************************************************************
             * 
             ***************************************************************************************************/
            modelBuilder.Entity<Consultation>()
                        .HasRequired(Consultation => Consultation.Patient)
                        .WithMany(Patient => Patient.Consultations)
                        .HasForeignKey(Consultation => Consultation.PatientID)
                        .WillCascadeOnDelete(true);

            modelBuilder.Entity<Consultation>()
                        .HasOptional(Consultation => Consultation.Ordonnance)
                        .WithMany()
                        .HasForeignKey(Consultation => Consultation.OrdonnanceID)
                        .WillCascadeOnDelete(false);

            modelBuilder.Entity<Document>()
                        .HasRequired(Document => Document.Patient)
                        .WithMany()
                        .HasForeignKey(Document => Document.PatientID)
                        .WillCascadeOnDelete(false);

            modelBuilder.Entity<ArretMaladie>()
                        .HasOptional(ArretMaladie => ArretMaladie.DossierMedical)
                        .WithMany(DossierMedical => DossierMedical.ArretsMaladie)
                        .HasForeignKey(ArretMaladie => ArretMaladie.DossierMedicalID)
                        .WillCascadeOnDelete(false);

            modelBuilder.Entity<Ordonnance>()
                        .HasOptional(Ordonnance => Ordonnance.DossierMedical)
                        .WithMany(DossierMedical => DossierMedical.Ordonnances)
                        .HasForeignKey(Ordonnance => Ordonnance.DossierMedicalID)
                        .WillCascadeOnDelete(false);

            modelBuilder.Entity<OperationChirurgicale>()
                        .HasOptional(OperationChirurgicale => OperationChirurgicale.DossierMedical)
                        .WithMany(DossierMedical => DossierMedical.OperationChirurgicales)
                        .HasForeignKey(OperationChirurgicale => OperationChirurgicale.DossierMedicalID)
                        .WillCascadeOnDelete(false);

            modelBuilder.Entity<Ordonnance>()
                        .HasRequired(Ordonnance => Ordonnance.Consultation)
                        .WithMany()
                        .HasForeignKey(Ordonnance => Ordonnance.ConsultationID)
                        .WillCascadeOnDelete(false);

            modelBuilder.Entity<OrdonnancesMedicaments>()
                        .HasRequired(OrdonnancesMedicaments => OrdonnancesMedicaments.Ordonnance)
                        .WithMany(Ordonnance => Ordonnance.OrdonnancesMedicaments)
                        .HasForeignKey(OrdonnancesMedicaments => OrdonnancesMedicaments.OrdonnanceID)
                        .WillCascadeOnDelete(true);

            modelBuilder.Entity<OrdonnancesMedicaments>()
                        .HasRequired(OrdonnancesMedicaments => OrdonnancesMedicaments.Medicament)
                        .WithMany(Medicament => Medicament.OrdonnancesMedicaments)
                        .HasForeignKey(OrdonnancesMedicaments => OrdonnancesMedicaments.MedicamentID)
                        .WillCascadeOnDelete(true);

            modelBuilder.Entity<Patient>()
                        .HasOptional(Patient => Patient.Document)
                        .WithMany()
                        .HasForeignKey(Patient => Patient.DocumentID)
                        .WillCascadeOnDelete(false);

            Database.SetInitializer(new App_cliniqueInitializer());
            base.OnModelCreating(modelBuilder);
        }

        public void BackUp(String BackupPath)
        {
            using (App_cliniqueContext db = new App_cliniqueContext())
            {
                db.Database.Connection.Open();

                DbCommand cmd = db.Database.Connection.CreateCommand();
                cmd.CommandText = "DatabaseBackup";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new SqlParameter { ParameterName = "@path", Value = BackupPath, DbType = DbType.String, Direction = ParameterDirection.Input });

                Directory.CreateDirectory(Path.GetDirectoryName(BackupPath));
                cmd.ExecuteReader();
            }
        }
    }

    public class App_cliniqueInitializer : DropCreateDatabaseIfModelChanges<App_cliniqueContext>
    {
        protected override void Seed(App_cliniqueContext context)
        {
            /****************************************************************************************************
             * Procedure stockées
             ***************************************************************************************************/
            StringBuilder ProcedureStockee = new StringBuilder();
            ProcedureStockee = Entete("Maxime", "AUBRY", "Backup de la base de données");
            ProcedureStockee.AppendLine("CREATE PROCEDURE [DatabaseBackup] (@path nvarchar(255))");
            ProcedureStockee.AppendLine("AS");
            ProcedureStockee.AppendLine("BEGIN");
            ProcedureStockee.Append("\t").AppendLine("BACKUP DATABASE [App_cliniqueContext] TO  DISK = @path WITH NOFORMAT, NOINIT,  NAME = N'App_cliniqueContext-Complète Base de données Sauvegarde', SKIP, NOREWIND, NOUNLOAD,  STATS = 10");
            ProcedureStockee.AppendLine("END");
        }

        private StringBuilder Entete(String Prenom, String Nom, String Description)
        {
            StringBuilder str = new StringBuilder();
            str.Append("-- =============================================");
            str.AppendLine(String.Format("-- Author:		{0} {1}", Prenom, Nom));
            str.AppendLine(String.Format("-- Create date:		{0}", DateTime.Now.ToString("F")));
            str.AppendLine(String.Format("-- Description:		{0}", Description));
            str.AppendLine("-- =============================================");

            return str;
        }
    }
}
